package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.DyOrderImportListener;
import com.settlement.system.listener.easyexcel.SubjectsImportListener;
import com.settlement.system.model.entity.SysSubjects;
import com.settlement.system.model.form.SubjectsForm;
import com.settlement.system.model.query.AuditPageQuery;
import com.settlement.system.model.query.SubjectsPageQuery;
import com.settlement.system.model.vo.DyOrderImportVo;
import com.settlement.system.model.vo.SubjectsImportVo;
import com.settlement.system.model.vo.SysAuditExportVO;
import com.settlement.system.model.vo.SysSubjectsVO;
import com.settlement.system.service.SysSubjectsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 科目设置 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2023-09-07
 */
@Tag(name = "科目表")
@RestController
@RequestMapping("/api/v1/subjects")
@RequiredArgsConstructor
public class SysSubjectsController {

    private final SysSubjectsService sysSubjectsService;

    @Operation(summary = "科目表分页列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysSubjectsVO> getPage(@ParameterObject SubjectsPageQuery queryParams) {
        Page<SysSubjectsVO> result = sysSubjectsService.getSubjectsPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "保存科目表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:subjects:save')")
    @PreventDuplicateSubmit
    public Result<?> saveSubjects(@RequestBody @Valid SubjectsForm subjectsForm) {
        boolean result = sysSubjectsService.saveSubjects(subjectsForm);
        return Result.judge(result);
    }

    @Operation(summary = "科目表单数据", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{subjectsId}/form")
    public Result<SysSubjects> getSubjectsForm(@Parameter(description = "科目表ID") @PathVariable Long subjectsId) {
        SysSubjects sysSubjects = sysSubjectsService.getSubjectsFormData(subjectsId);
        return Result.success(sysSubjects);
    }

    @Operation(summary = "根据入账主体查出科目列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/subjectsList")
    public Result<?> getSubjectsList(@ParameterObject SubjectsPageQuery queryParams) {
        List<SysSubjects> sysSubjects = sysSubjectsService.getSubjectsList(queryParams);
        return Result.success(sysSubjects);
    }

    @Operation(summary = "删除科目表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:subjects:delete')")
    public Result<?> deleteSubjects(@Parameter(description = "科目表ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysSubjectsService.deleteSubjects(ids);
        return Result.judge(result);
    }

    @Operation(summary = "导出科目", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    public void export(HttpServletResponse response) throws IOException {
        String fileName = "科目表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        EasyExcel.write(response.getOutputStream(), SubjectsImportVo.class).sheet("科目表").doWrite(new ArrayList<>());
    }

    @Operation(summary = "导入科目", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_import")
    public Result<?> subjectsImport(@RequestParam("file") MultipartFile file) throws Exception {
        SubjectsImportListener subjectsImportListener = new SubjectsImportListener();
        EasyExcelFactory.read(file.getInputStream(), SubjectsImportVo.class, subjectsImportListener).sheet(0).doRead();
        List<SubjectsImportVo> vos = subjectsImportListener.getVos();
        List<String> messages = sysSubjectsService.updateBatch(vos);
        return Result.success(messages);
    }
}
